// CRUD页面的JavaScript代码
let currentPage = 1;
let pageSize = 10;
let totalPages = 1;
let totalCount = 0;
let currentDeleteId = null;

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    loadData();
});

/**
 * 加载数据
 */
function loadData() {
    const params = new URLSearchParams({
        page: currentPage,
        pageSize: pageSize
    });

    fetch(`../ProductDataTableServlet?${params}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayCrudData(data);
                updateCrudPagination(data);
            } else {
                showError(data.message || '加载数据失败');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showError('网络错误，请稍后重试');
        });
}

/**
 * 显示CRUD数据
 */
function displayCrudData(data) {
    const tbody = document.getElementById('crudTableBody');
    
    if (!data.data || data.data.length === 0) {
        tbody.innerHTML = `
            <tr>
                <td colspan="6" class="empty-state">
                    <div class="empty-icon">📋</div>
                    <div class="empty-message">暂无数据</div>
                </td>
            </tr>
        `;
        return;
    }

    let html = '';
    data.data.forEach((record, index) => {
        html += `
            <tr>
                <td class="number-cell">${record.id}</td>
                <td>${escapeHtml(record.name)}</td>
                <td>${escapeHtml(record.number)}</td>
                <td>${escapeHtml(record.price)}</td>
                <td class="date-cell">${formatDate(record.madetime)}</td>
                <td class="action-buttons">
                    <button class="btn btn-warning btn-sm" onclick="handleEdit(${index})">编辑</button>
                    <button class="btn btn-danger btn-sm" onclick="handleDelete(${index})">删除</button>
                </td>
            </tr>
        `;
    });
    
    // 将数据存储在全局变量中供按钮使用
    window.currentTableData = data.data;
    tbody.innerHTML = html;
}

/**
 * 更新CRUD分页控件
 */
function updateCrudPagination(data) {
    totalPages = data.totalPages;
    totalCount = data.totalCount;

    const pagination = document.getElementById('crudPagination');
    let html = '';

    // 上一页按钮
    html += `<button onclick="previousPage()" ${currentPage <= 1 ? 'disabled' : ''}>上一页</button>`;

    // 页码按钮
    const startPage = Math.max(1, currentPage - 2);
    const endPage = Math.min(totalPages, currentPage + 2);

    if (startPage > 1) {
        html += `<button onclick="goToPage(1)">1</button>`;
        if (startPage > 2) {
            html += `<span>...</span>`;
        }
    }

    for (let i = startPage; i <= endPage; i++) {
        html += `<button onclick="goToPage(${i})" ${i === currentPage ? 'class="current-page"' : ''}>${i}</button>`;
    }

    if (endPage < totalPages) {
        if (endPage < totalPages - 1) {
            html += `<span>...</span>`;
        }
        html += `<button onclick="goToPage(${totalPages})">${totalPages}</button>`;
    }

    // 下一页按钮
    html += `<button onclick="nextPage()" ${currentPage >= totalPages ? 'disabled' : ''}>下一页</button>`;

    pagination.innerHTML = html;
    
    // 更新页面信息显示
    const pageInfo = document.getElementById('crudPageInfo');
    if (pageInfo) {
        pageInfo.innerHTML = `第 ${currentPage} 页，共 ${totalPages} 页`;
    }
}

/**
 * 分页函数
 */
function goToPage(page) {
    currentPage = page;
    loadData();
}

function previousPage() {
    if (currentPage > 1) {
        currentPage--;
        loadData();
    }
}

function nextPage() {
    if (currentPage < totalPages) {
        currentPage++;
        loadData();
    }
}

/**
 * 处理编辑按钮点击
 */
function handleEdit(index) {
    const record = window.currentTableData[index];
    editRecord(record.id, record.name, record.number, record.price, record.madetime);
}

/**
 * 处理删除按钮点击
 */
function handleDelete(index) {
    const record = window.currentTableData[index];
    deleteRecord(record.id, record.name);
}

/**
 * 显示添加记录模态框
 */
function showAddModal() {
    document.getElementById('modalTitle').textContent = '添加新记录';
    document.getElementById('recordForm').reset();
    document.getElementById('recordId').value = '';
    document.getElementById('recordModal').style.display = 'flex';
}

/**
 * 编辑记录
 */
function editRecord(id, name, number, price, madetime) {
    document.getElementById('modalTitle').textContent = '编辑记录';
    document.getElementById('recordId').value = id;
    document.getElementById('recordName').value = name;
    document.getElementById('recordNumber').value = number;
    document.getElementById('recordPrice').value = price;
    
    // 处理日期格式
    if (madetime) {
        const date = new Date(madetime);
        const formattedDate = date.getFullYear() + '-' + 
            String(date.getMonth() + 1).padStart(2, '0') + '-' + 
            String(date.getDate()).padStart(2, '0');
        document.getElementById('recordMadetime').value = formattedDate;
    }
    
    document.getElementById('recordModal').style.display = 'flex';
}

/**
 * 删除记录
 */
function deleteRecord(id, name) {
    currentDeleteId = id;
    document.getElementById('deleteRecordInfo').textContent = `记录: ${name} (ID: ${id})`;
    document.getElementById('deleteModal').style.display = 'flex';
}

/**
 * 保存记录
 */
function saveRecord() {
    const form = document.getElementById('recordForm');
    const formData = new FormData(form);
    
    // 验证表单
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    const data = {
        action: formData.get('id') ? 'update' : 'create',
        id: formData.get('id'),
        name: formData.get('name'),
        number: formData.get('number'),
        price: formData.get('price'),
        madetime: formData.get('madetime')
    };
    
    fetch('../ProductDataTableServlet', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showSuccess(result.message || '操作成功');
            closeModal();
            loadData();
        } else {
            showError(result.message || '操作失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showError('网络错误，请稍后重试');
    });
}

/**
 * 确认删除
 */
function confirmDelete() {
    if (!currentDeleteId) return;
    
    const data = {
        action: 'delete',
        id: currentDeleteId
    };
    
    fetch('../ProductDataTableServlet', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            showSuccess(result.message || '删除成功');
            closeDeleteModal();
            loadData();
        } else {
            showError(result.message || '删除失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        showError('网络错误，请稍后重试');
    });
}

/**
 * 关闭模态框
 */
function closeModal() {
    document.getElementById('recordModal').style.display = 'none';
}

function closeDeleteModal() {
    document.getElementById('deleteModal').style.display = 'none';
    currentDeleteId = null;
}

/**
 * 显示错误信息
 */
function showError(message) {
    const errorDiv = document.getElementById('errorMessage');
    errorDiv.textContent = message;
    errorDiv.style.display = 'block';
    setTimeout(() => {
        errorDiv.style.display = 'none';
    }, 5000);
}

/**
 * 显示成功信息
 */
function showSuccess(message) {
    const successDiv = document.getElementById('successMessage');
    successDiv.textContent = message;
    successDiv.style.display = 'block';
    setTimeout(() => {
        successDiv.style.display = 'none';
    }, 3000);
}

/**
 * HTML转义函数
 */
function escapeHtml(text) {
    if (typeof text !== 'string') return text;
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}

/**
 * 格式化日期（仅日期部分）
 */
function formatDate(dateTimeStr) {
    if (!dateTimeStr) return '';
    
    try {
        const date = new Date(dateTimeStr);
        return date.getFullYear() + '-' +
            String(date.getMonth() + 1).padStart(2, '0') + '-' +
            String(date.getDate()).padStart(2, '0');
    } catch (e) {
        return dateTimeStr;
    }
}
